package model

import (
	"context"
	"fmt"

	"github.com/Masterminds/squirrel"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ SysLoginLogModel = (*customSysLoginLogModel)(nil)

type (
	// SysLoginLogModel is an interface to be customized, add more methods here,
	// and implement the added methods in customSysLoginLogModel.
	SysLoginLogModel interface {
		sysLoginLogModel
		RowBuilder() squirrel.SelectBuilder
		Truncate(ctx context.Context)
		FindAll(ctx context.Context) ([]*SysLoginLog, error)
		FindAllEx(Current int64, PageSize int64) (*[]SysLoginLog, error)
		Count() (int64, error)
	}

	customSysLoginLogModel struct {
		*defaultSysLoginLogModel
	}
)

// NewSysLoginLogModel returns a model for the database table.
func NewSysLoginLogModel(conn sqlx.SqlConn, c cache.CacheConf) SysLoginLogModel {
	return &customSysLoginLogModel{
		defaultSysLoginLogModel: newSysLoginLogModel(conn, c),
	}
}

func (m *defaultSysLoginLogModel) RowBuilder() squirrel.SelectBuilder {
	return squirrel.Select(sysLoginLogRows).From(m.table)
}

func (m defaultSysLoginLogModel) Truncate(ctx context.Context) {
	build := m.RowBuilder()
	query, values, err := build.ToSql()
	if err == nil {
		var resp []*SysLoginLog
		err = m.QueryRowsNoCacheCtx(ctx, &resp, query, values...)
		if err == nil {
			for _, r := range resp {
				m.Delete(ctx, r.Id)
			}
			m.ExecNoCacheCtx(ctx, fmt.Sprintf("TRUNCATE %s", m.tableName()))
		}
	}
}

func (m defaultSysLoginLogModel) FindAll(ctx context.Context) ([]*SysLoginLog, error) {
	build := m.RowBuilder()
	query, values, err := build.ToSql()
	if err != nil {
		return nil, nil
	}

	var resp []*SysLoginLog
	err = m.QueryRowsNoCacheCtx(ctx, &resp, query, values...)
	switch err {
	case nil:
		return resp, nil
	default:
		return nil, err
	}
}

func (m *defaultSysLoginLogModel) FindAllEx(Current int64, PageSize int64) (*[]SysLoginLog, error) {

	query := fmt.Sprintf("select %s from %s limit ?,?", sysLoginLogRows, m.table)
	var resp []SysLoginLog
	err := m.CachedConn.QueryRowsNoCache(&resp, query, (Current-1)*PageSize, PageSize)
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *defaultSysLoginLogModel) Count() (int64, error) {
	query := fmt.Sprintf("select count(*) as count from %s", m.table)

	var count int64
	err := m.CachedConn.QueryRowNoCache(&count, query)

	switch err {
	case nil:
		return count, nil
	case sqlc.ErrNotFound:
		return 0, ErrNotFound
	default:
		return 0, err
	}
}
